package com.bsu.database.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.bsu.bean.Blog;
import com.bsu.util.HibernateUtil;

public class BlogDAO {
	private Logger logger = Logger.getLogger(BlogDAO.class);

	@SuppressWarnings("unchecked")
	public List<Blog> getList(int idUser) throws ClassNotFoundException, SQLException {
		
			List<Blog> blogsList = new ArrayList<Blog>();
			Session session = HibernateUtil.getSessionfactory().openSession();
			Transaction transaction = null;
			try {
				transaction = session.beginTransaction();
				blogsList = session.getNamedQuery("LIST_BLOGS").setParameter(0, idUser).list();
				transaction.commit();
			} catch (HibernateException e) {
				transaction.rollback();
				logger.error(e.toString());
			} 
			return blogsList;

		
	}

	public Blog get(int idBlog) throws ClassNotFoundException {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		Blog blog = null;
		try {
			transaction = session.beginTransaction();
			blog = (Blog) session.get(Blog.class, idBlog);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			logger.error(e.toString());
		} 
		return blog;

		
	}

	public boolean add(Blog blog) throws ClassNotFoundException {
		Session session = HibernateUtil.getSessionfactory().openSession();

		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.saveOrUpdate(blog);
			transaction.commit();
			return true;
		} catch (HibernateException e) {
			transaction.rollback();
			logger.error(e.toString());
		}

		return false;
	}

	public void update(Blog blog) {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.saveOrUpdate(blog);
			transaction.commit();
			
		} catch (HibernateException e) {
			transaction.rollback();
			logger.error(e.toString());
		}

	}
	
	public void delete(int id) throws ClassNotFoundException {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Query query = session.getNamedQuery("REMOVE");
			query.setParameter("idBlog", id);
			query.executeUpdate();
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			logger.error(e.toString());
		}
		
	}
	


}
